package com.jinlejia.erp.ui.house.prospect;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.text.TextUtils;

import com.donkingliang.imageselector.utils.ImageSelector;
import com.jinlejia.erp.BuildConfig;
import com.jinlejia.erp.adapter.prospect.UploadImageGridViewAdapter;
import com.jinlejia.erp.ui.house.prospect.bean.RoomBean;
import com.jinlejia.erp.ui.house.prospect.bean.SurveyPictureBean;
import com.jinlejia.erp.widget.prospect.NoScrollGridView;
import com.jinlejia.erp.widget.prospect.ProspectUploadHeaderView;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import top.zibin.luban.LubanZ;

/**
 * 封装房源实勘图片的公共方法
 * @author 王进 on 2019/1/9.
 */

class FragmentHelper implements ProspectUploadImageActivity.HousePictureListener {

    public static ProspectUploadImageActivity.HousePictureListener newInstance(int pageType, int usage, String houseType, String houseSourceCode, String houseSourceType, SurveyPictureBean bean){
        ProspectUploadImageActivity.HousePictureListener listener;
        switch (usage){
            case Type.USAGE_RESIDENTIAL:
                listener = new ProspectUploadResidentialFragment();
                break;
            case Type.USAGE_APARTMENT:
                listener = new ProspectUploadApartmentFragment();
                break;
            case Type.USAGE_VILLA:
                listener = new ProspectUploadVillaFragment();
                break;
            case Type.USAGE_OFFICE:
                listener = new ProspectUploadOfficeFragment();
                break;
            case Type.USAGE_SHOP:
                listener = new ProspectUploadShopFragment();
                break;
            case Type.USAGE_WAREHOUSE:
                listener = new ProspectUploadWarehouseFragment();
                break;
            default:
                throw new IllegalArgumentException();
        }
        Fragment fragment = (Fragment) listener;
        Bundle args = new Bundle();
        args.putString(Type.PARAM.HOUSE_TYPE, houseType);
        args.putString(Type.PARAM.HOUSE_SOURCE_CODE,houseSourceCode);
        args.putString(Type.PARAM.HOUSE_SOURCE_TYPE,houseSourceType);
        args.putInt(Type.PARAM.PAGE_TYPE,pageType);
        args.putParcelable(Type.PARAM.HOUSE_SOURCE_INFO,bean);
        fragment.setArguments(args);
        return listener;
    }


    SurveyPictureBean getSourceInfo(){
        Bundle arguments = fragment.getArguments();
        if (arguments!=null){
            return arguments.getParcelable(Type.PARAM.HOUSE_SOURCE_INFO);
        }
        return null;
    }

    private int getPageShowType(){
        Bundle arguments = fragment.getArguments();
        if (arguments!=null){
            return arguments.getInt(Type.PARAM.PAGE_TYPE);
        }
        return 0;
    }



    private class Source{
        Source(NoScrollGridView gridView,ProspectUploadHeaderView headerView,UploadImageGridViewAdapter adapter){
            this.gridView = gridView;
            this.headerView = headerView;
            this.adapter = adapter;
        }
        UploadImageGridViewAdapter adapter;
        ProspectUploadHeaderView headerView;
        NoScrollGridView gridView;
    }

    private ArrayList<Source> cacheArray;
    //缓存相册选择器的照片
    private ArrayList<String> cachePicture = new ArrayList<>();
    private Fragment fragment;
    private String houseSourceCode,houseSourceType;
    private Helper helper;
    private FragmentHelper(Fragment fragment,String houseSourceCode, String houseSourceType,Helper helper){
        this.fragment = fragment;
        cacheArray = new ArrayList<>();
        this.houseSourceCode = houseSourceCode;
        this.houseSourceType = houseSourceType;
        this.helper = helper;
    }
    public static FragmentHelper init(Fragment fragment, String houseSourceCode, String houseSourceType,Helper helper){
        return new FragmentHelper(fragment,houseSourceCode,houseSourceType,helper);
    }

    void onActivityResult(int requestCode, int resultCode, Intent data){
        if (resultCode != Activity.RESULT_OK) return;
        UploadImageGridViewAdapter subdividedAdapter = getSubdividedAdapter(requestCode);
        if (subdividedAdapter!=null){ //如果是获取区间信息
            UploadImageGridViewAdapter.Source source = data.getParcelableExtra("data");
            if (source == null) {
                if (BuildConfig.DEBUG) {
                    throw new IllegalArgumentException("没有获取到区间信息");
                }
                return;
            }
            subdividedAdapter.updateSourceInfo(source);
            subdividedAdapter.notifyDataSetChanged();
            return;
        }
        final UploadImageGridViewAdapter pictureAdapter = getPictureAdapter(requestCode);
        if (pictureAdapter == null) return;
        //如果是获取图片信息
        ArrayList<String> list = data.getStringArrayListExtra(ImageSelector.SELECT_RESULT);
        ArrayList<UploadImageGridViewAdapter.Source> pictureSources = pictureAdapter.getSources();
        final ArrayList<LubanZ.LubanZImage> files = new ArrayList<>();
        for (String url : list) {
            //region 未使用，图片重复不允许添加。原因：功能不完善，各个图片适配器的图片判断需要额外成本
//            for (UploadImageGridViewAdapter.Source s:pictureSources) {
//                if (url.equals(s.getPictureUrl())){ //当选中的图片重复时
//                    CustomToast.showToast(fragment.getContext(),"图片已存在",1500);
//                    return;
//                }
//            }
            //endregion
            UploadImageGridViewAdapter.Source source = new UploadImageGridViewAdapter.Source();
            source.setPictureUrl(url);
            source.setUploadState(1); //上传图片的第一步，将上传图片的状态设置为 上传中
            pictureAdapter.addSource(source);
            LubanZ.LubanZImage image = new LubanZ.LubanZImage();
            File file = new File(url);
            if (file.exists()){
                image.setOriginalFile(file);
                files.add(image);
            }
        }
        innerUploadImage(files,pictureAdapter);
        pictureAdapter.notifyDataSetChanged();
        //region (未使用)缓存用户之前选中的照片，当用户再次选择照片时，将这些照片以选中的状态展示在图片选择器中
        /*
        ArrayList<UploadImageGridViewAdapter.Source> sources = pictureAdapter.getSources();
        cachePicture.clear();
        for (UploadImageGridViewAdapter.Source s:sources) {
            cachePicture.add(s.getPictureUrl());
        }
        */
        //endregion
    }

    private synchronized void toUpdateSource(String fileName, String serverUrl, ArrayList<String> failedList,UploadImageGridViewAdapter adapter) {
        ArrayList<UploadImageGridViewAdapter.Source> sources = adapter.getSources();
        for (int i = 0; i < sources.size(); i++) {
            final UploadImageGridViewAdapter.Source source = sources.get(i);
            String pictureUrl = source.getPictureUrl();
            if (failedList == null || failedList.isEmpty()) {
                if (!TextUtils.isEmpty(serverUrl)
                        && !TextUtils.isEmpty(pictureUrl)
                        && URLEncoder.encode(pictureUrl).equals(fileName)) {
                    source.setServerUrl(serverUrl);
                    source.setUploadState(0); //标识上传成功
                    adapter.updateSource(source);
                }
            } else {
                for (String u : failedList) {
                    String url = URLEncoder.encode(source.getPictureUrl());
                    if (url.equals(u)) {
                        source.setUploadState(2);
                        adapter.updateSource(source);
                        break;
                    }
                }
            }
        }
        adapter.notifyDataSetInvalidated();
    }

    private void innerUploadImage(final ArrayList<LubanZ.LubanZImage> files, final UploadImageGridViewAdapter adapter) {
        ArrayList<UploadImageGridViewAdapter.Source> sources = adapter.getSources();
        helper.http().uploadImage(sources, files, new Helper.Http.UploadImageCallBack() {


            @Override
            public void onUploadSuccess(String fileName, String serverUrl) {
                toUpdateSource(fileName, serverUrl, null,adapter);
            }

            @Override
            public void onUploadComplete(ArrayList<String> failedList) {
                if (failedList != null && !failedList.isEmpty()) {
                    toUpdateSource(null, null, failedList,adapter);
                }
            }
        });

    }

    void createAdapterAndSetToGridView(final NoScrollGridView gridView,final ProspectUploadHeaderView view,
                                       int count,boolean isMust,boolean hasSubdivided){
        createAdapterAndSetToGridView(gridView,view,count,isMust,0,hasSubdivided);
    }

    /**
     * 创建Adapter
     * @param count 要显示的数量
     * @param isMust 是否是必填
     * @param maxCount 最大数字
     * @param hasSubdivided true 需要选择分间信息 false 不需要选择分间信息
     */
    void createAdapterAndSetToGridView(final NoScrollGridView gridView,final ProspectUploadHeaderView view,
                                       int count,boolean isMust,int maxCount,boolean hasSubdivided){
        view.setNum(count,maxCount);
        view.setMust(isMust);
        int count_;
        if (maxCount!=0){
            count_ = maxCount;
        }else {
            count_ = count;
        }
        UploadImageGridViewAdapter adapter = new UploadImageGridViewAdapter(view.getLabel(),fragment.getContext(), count_,hasSubdivided, new UploadImageGridViewAdapter.UploadListener() {
            @Override
            public void onSelectPicture(int lastShowCount) {
                toSelectPictureActivity(view,lastShowCount);
            }

            @Override
            public void onSelectSubdivided(ArrayList<UploadImageGridViewAdapter.Source> sources, UploadImageGridViewAdapter.Source source) {
                toSelectSubdividedActivity(sources,view, source);
            }

            @Override
            public void onPreviewViePicture(ArrayList<UploadImageGridViewAdapter.Source> sources, int position, UploadImageGridViewAdapter.Source source) {
                toPreviewPictureActivity(sources,position);
            }

            @Override
            public void onReloadPicture(UploadImageGridViewAdapter.Source source) {
                ArrayList<LubanZ.LubanZImage> files = new ArrayList<>();
                LubanZ.LubanZImage image = new LubanZ.LubanZImage();
                File file = new File(source.getPictureUrl());
                image.setOriginalFile(file);
                files.add(image);
                innerUploadImage(files, (UploadImageGridViewAdapter) gridView.getAdapter());
            }
        });
        Source source = new Source(gridView, view, adapter);
        cacheArray.add(source);
        gridView.setAdapter(adapter);
    }


    void updateAdapterSource(final NoScrollGridView gridView,final ProspectUploadHeaderView view){
        UploadImageGridViewAdapter adapter = (UploadImageGridViewAdapter) gridView.getAdapter();
        if (adapter==null)return;
        SurveyPictureBean info = getSourceInfo();
        if (info==null)return;
        String label = view.getLabel();
        List<RoomBean> list = null;
        if (label.contains("厅")){
            list = info.getHall();
        }else if (label.contains("室")){
            if (label.contains("游戏室")){
                list = info.getPlayRoom();
            }else if (label.contains("棋牌室")){
                list = info.getChessRoom();
            }else if (label.contains("室内照片")){
                list = info.getIndoor();
            }else if (label.contains("室外风景图")){
                list = info.getScenery();
            }else if (label.contains("地下室")){
                list = info.getUnderground();
            } else {
                list = info.getRoom();
            }
        }else if (label.contains("卫")){
            list = info.getToilet();
        }else if (label.contains("厨")){
            list = info.getKitchen();
        }else if (label.contains("阳台")){
            list = info.getBalcony();
        }else if (label.contains("车位")){
            list = info.getParkingSpace();
        }else if (label.contains("院")){
            list = info.getYard();
        }else if (label.contains("储物间")){
            list = info.getLockerRoom();
        }else if (label.contains("衣帽间")){
            list = info.getCloakRoom();
        }else if (label.contains("洗衣间")){
            list = info.getLaundryRoom();
        }else if (label.contains("露台")){
            list = info.getTerrace();
        }else if (label.contains("楼体正面全景")){
            list = info.getBuilding();
        }else if (label.contains("玄关")){
            list = info.getVestibule();
        }else if (label.contains("保姆间")){
            list = info.getNannyRoom();
        }else if (label.contains("阳光房")){
            list = info.getSunRoom();
        }else if (label.contains("游戏室")){
            list = info.getPlayRoom();
        }else if (label.contains("棋牌室")){
            list = info.getChessRoom();
        }else if (label.contains("楼体外景")){
            list = info.getOutdoorScene();
        }else if (label.contains("大堂")){
            list = info.getLobby();
        }else if (label.contains("街景")){
            list = info.getStreetScape();
        }else if (label.contains("门头")){
            list = info.getDoorWay();
        }else if (label.contains("阁楼")){
            list = info.getAttic();
        }
        if (list != null) {
            String[]labels = null;
            if (label.contains("院")){
                labels= new String[]{"前院","后院","侧院A","侧院B"};
            }
            for (int i = 0;i<list.size();i++) {
                RoomBean b = list.get(i);
                UploadImageGridViewAdapter.Source s = new UploadImageGridViewAdapter.Source();
                String windows = b.getWindows();
                s.setWindows(windows);  //窗户种类
                String face = b.getFace();
                s.setOrientation(face); //房屋朝向
                String name = b.getName();
                if (labels!=null){
                    if (i>=labels.length-1){
                        name = labels[i];
                    }
                }
                s.setHouseName(name);   //房屋名称
                String pictureUrl = b.getUrl();
                s.setPictureUrl(pictureUrl);//图片地址
                s.setServerUrl(pictureUrl); //存储服务器的地址
                String square = b.getSquare();
                if (!TextUtils.isEmpty(square) && !"null".equalsIgnoreCase(square)){
                    s.setAcreage(square);  //房屋面积
                }
                adapter.addSource(s);
            }
        }
        adapter.notifyDataSetInvalidated();
    }

    /**
     * 检查数据，返回错误提示信息
     */
    private String check(final ProspectUploadHeaderView view, UploadImageGridViewAdapter adapter){
        if (adapter == null) return null; //如果某一列没有展示，则不进行判断。
        boolean must = view.isMust();
        String label = view.getLabel();
        int showNumber = view.getShowNumber();
        String message = null;
        ArrayList<UploadImageGridViewAdapter.Source> sources = adapter.getSources();
        int count = adapter.getSourceCount();
        if (must) {
            if ("院".equals(label)){ //院的特殊处理
                if (count==0){
                    message = String.format("[%s]户型图至少上传一张，请继续传图",label);
                    return message;
                }
            }else if (showNumber > count) {
                message = String.format("[%s]户型图片数量过少，请继续传图",label);
                return message;
            }
        }
        for (int i = 0; i < sources.size(); i++) {
            UploadImageGridViewAdapter.Source s = sources.get(i);
            if ("院".equals(label)){
                if (i==0){
                    s.setHouseName("前院");
                }else if (i==1){
                    s.setHouseName("后院");
                }else {
                    String name = "侧院"+((char) ('A'+(i-2)));
                    s.setHouseName(name);
                }
            }else if ("室外风景图".equals(label)){
                if (i>0){
                    s.setHouseName("室外风景图"+((char)('A'+i)));
                }else {
                    s.setHouseName("室外风景图");
                }
            }
            if (s.getUploadState()==1){
                message = String.format("[%s]图片正在上传中,请稍后...", label);
                break;
            }
            if (!TextUtils.isEmpty(s.getPictureUrl()) ) { //当设置了图片信息
                if (adapter.isHasSubdivided()){ //当需要设置分间信息时
                    if (TextUtils.isEmpty(s.getHouseName()) || "null".equalsIgnoreCase(s.getHouseName())){
                        message = String.format("[%s]未设置分间信息，请点击分间名称来设置", label);
                        break;
                    }
                }

            }
            if (s.getUploadState()!=0){
                message = String.format("[%s]图片信息有误，请重新上传", label);
                break;
            }
        }
        return message;
    }

    private int findIndexInCacheArrayByHeaderViewId(int headerViewId){
        for (int i = 0; i < cacheArray.size(); i++) {
            Source source = cacheArray.get(i);
            if (source.headerView.getId()==headerViewId){
                return i;
            }
        }
        return -1;
    }

    private void toSelectPictureActivity(ProspectUploadHeaderView view,int lastShowCount){
        int indexOf = findIndexInCacheArrayByHeaderViewId(view.getId());
        int pictureRequestCode = indexOf+101;
        ImageSelector.builder()
                .useCamera(true)
                .setMaxSelectCount(lastShowCount)
                .setSelected(cachePicture)
                .setViewImage(true)
                .start(fragment, pictureRequestCode);
    }

    //根据requestCode获取要进行更新图片信息的Adapter
    private UploadImageGridViewAdapter getPictureAdapter(int requestCode){
        int at = requestCode-101;
        if (at<0 || at>=this.cacheArray.size()){
            return null;
        }
        return this.cacheArray.get(at).adapter;
    }

    @Nullable
    private UploadImageGridViewAdapter getSubdividedAdapter(int requestCode){
        int at = requestCode-201;
        if (at<0 || at>=this.cacheArray.size()){
            return null;
        }
        return this.cacheArray.get(at).adapter;
    }
    //跳转到预览界面
    private void toPreviewPictureActivity(ArrayList<UploadImageGridViewAdapter.Source> sources,int position){
        Intent intent = new Intent();
        intent.setClass(fragment.getContext(),ProspectViewPictureActivity.class);
        intent.putExtra(ProspectViewPictureActivity.PARAM_SOURCES,sources);
        intent.putExtra(ProspectViewPictureActivity.PARAM_POSITION,position);
        fragment.startActivity(intent);
    }
    //获取分间信息
    private void toSelectSubdividedActivity(ArrayList<UploadImageGridViewAdapter.Source> sources, ProspectUploadHeaderView view, UploadImageGridViewAdapter.Source source){
        int indexOf = findIndexInCacheArrayByHeaderViewId(view.getId());
        int showType = getPageShowType();
        int requestCode = indexOf+201;
        int count = view.getMaxCount();
        if (count==0){
            count = view.getShowNumber();
        }
        Intent intent = new Intent(fragment.getContext(), ProspectSubdividedActivity.class);
        intent.putExtra(Type.PARAM.HOUSE_SOURCE_CODE,houseSourceCode);
        intent.putExtra(Type.PARAM.HOUSE_SOURCE_TYPE,houseSourceType);
        intent.putExtra(Type.PARAM.SUBDIVIDED_LABEL,view.getLabel());
        intent.putExtra(Type.PARAM.SUBDIVIDED_COUNT,count);
        intent.putExtra(Type.PARAM.PAGE_TYPE,showType);
        intent.putExtra(ProspectSubdividedActivity.PARAM_SOURCE, source);
        intent.putExtra(ProspectSubdividedActivity.PARAM_ALL_SOURCE, sources);
        fragment.startActivityForResult(intent, requestCode);
    }

    @Override
    public String checkPicturesResult() {
        for (int i = 0; i < cacheArray.size(); i++) {
            UploadImageGridViewAdapter adapter = cacheArray.get(i).adapter;
            ProspectUploadHeaderView headerView = cacheArray.get(i).headerView;
            String check = check(headerView, adapter);
            if (!TextUtils.isEmpty(check)){
                return check;
            }
        }
        return null;
    }

    @Override
    public SurveyPictureBean getPicturesResult() {
        SurveyPictureBean info = new SurveyPictureBean();
        for (int i = 0; i < cacheArray.size(); i++) {
            UploadImageGridViewAdapter adapter = cacheArray.get(i).adapter;
            ProspectUploadHeaderView headerView = cacheArray.get(i).headerView;
            String label = headerView.getLabel();
            List<RoomBean> list;
            if (label.contains("厅")){
                list = convertAdapterSourceToRoomBeanList(adapter.getSources());
                info.setHall(list);
            }else if (label.contains("室")){
                if (label.contains("游戏室")){
                    //
                    list = convertAdapterSourceToRoomBeanList(adapter.getSources());
                    info.setPlayRoom(list);
                }else if (label.contains("棋牌室")){
                    //
                    list = convertAdapterSourceToRoomBeanList(adapter.getSources());
                    info.setChessRoom(list);
                }else if (label.contains("室内照片")){
                    //
                    list = convertAdapterSourceToRoomBeanList(adapter.getSources());
                    info.setIndoor(list);
                }else if (label.contains("室外风景图")){
                    list = convertAdapterSourceToRoomBeanList(adapter.getSources());
                    info.setScenery(list);
                }else if (label.contains("地下室")){
                    list = convertAdapterSourceToRoomBeanList(adapter.getSources());
                    info.setUnderground(list);
                }else {
                    //室
                    list = convertAdapterSourceToRoomBeanList(adapter.getSources());
                    info.setRoom(list);
                }
            }else if (label.contains("卫")){
                //
                list = convertAdapterSourceToRoomBeanList(adapter.getSources());
                info.setToilet(list);
            }else if (label.contains("厨")){
                //
                list = convertAdapterSourceToRoomBeanList(adapter.getSources());
                info.setKitchen(list);
            }else if (label.contains("阳台")){
                //
                list = convertAdapterSourceToRoomBeanList(adapter.getSources());
                info.setBalcony(list);

            }else if (label.contains("车位")){
                //
                list = convertAdapterSourceToRoomBeanList(adapter.getSources());
                info.setParkingSpace(list);
            }else if (label.contains("院")){
                //
                list = convertAdapterSourceToRoomBeanList(adapter.getSources());
                info.setYard(list);
            }else if (label.contains("储物间")){
                //
                list = convertAdapterSourceToRoomBeanList(adapter.getSources());
                info.setLockerRoom(list);
            }else if (label.contains("衣帽间")){
                //
                list = convertAdapterSourceToRoomBeanList(adapter.getSources());
                info.setCloakRoom(list);
            }else if (label.contains("洗衣间")){
                //
                list = convertAdapterSourceToRoomBeanList(adapter.getSources());
                info.setLaundryRoom(list);
            }else if (label.contains("露台")){
                list = convertAdapterSourceToRoomBeanList(adapter.getSources());
                info.setTerrace(list);
            }else if (label.contains("楼体正面全景")){
                //
                list = convertAdapterSourceToRoomBeanList(adapter.getSources());
                info.setBuilding(list);
            }else if (label.contains("玄关")){
                //
                list = convertAdapterSourceToRoomBeanList(adapter.getSources());
                info.setVestibule(list);
            }else if (label.contains("保姆间")){
                //
                list = convertAdapterSourceToRoomBeanList(adapter.getSources());
                info.setNannyRoom(list);
            }else if (label.contains("阳光房")){
                //
                list = convertAdapterSourceToRoomBeanList(adapter.getSources());
                info.setSunRoom(list);
            }else if (label.contains("游戏室")){
                //
                list = convertAdapterSourceToRoomBeanList(adapter.getSources());
                info.setPlayRoom(list);
            }else if (label.contains("棋牌室")){
                //
                list = convertAdapterSourceToRoomBeanList(adapter.getSources());
                info.setChessRoom(list);
            }else if (label.contains("楼体外景")){
                //
                list = convertAdapterSourceToRoomBeanList(adapter.getSources());
                info.setOutdoorScene(list);
            }else if (label.contains("大堂")){
                //
                list = convertAdapterSourceToRoomBeanList(adapter.getSources());
                info.setLobby(list);
            }else if (label.contains("室外风景图")){
                //
                list = convertAdapterSourceToRoomBeanList(adapter.getSources());
                info.setScenery(list);
            }else if (label.contains("街景")){
                //
                list = convertAdapterSourceToRoomBeanList(adapter.getSources());
                info.setStreetScape(list);
            }else if (label.contains("门头")){
                //
                list = convertAdapterSourceToRoomBeanList(adapter.getSources());
                info.setDoorWay(list);
            }else if (label.contains("阁楼")){
                list = convertAdapterSourceToRoomBeanList(adapter.getSources());
                info.setAttic(list);
            }


        }
        return info;
    }

    private List<RoomBean> convertAdapterSourceToRoomBeanList(ArrayList<UploadImageGridViewAdapter.Source> sources){
        List<RoomBean> list = new ArrayList<>();
        RoomBean room;
        for (UploadImageGridViewAdapter.Source s: sources) {
            room = new RoomBean();
            room.setName(s.getHouseName()); //名称
            room.setSquare(s.getAcreage()); //面积
            room.setFace(s.getOrientation());   //朝向
            room.setUrl(s.getServerUrl()); //图片地址
            room.setWindows(s.getWindows()); //窗户种类
            list.add(room);
        }
        return list;
    }
}
